import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const baseURL = process.env.VUE_APP_BASE_URL
const service = axios.create({
  baseURL: baseURL, // api base_url
  timeout: 6000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  const tag = Vue.ls.get('JULIWEI-TAG')
  const version = Vue.ls.get('VERSION')
  if (token) {
    config.headers['TOKEN'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  if (tag) {
    config.headers['JULIWEI-TAG'] = tag // 让每个请求携带自定义 JULIWEI-TAG 请根据实际情况自行修改
  }
  if (version) {
    config.headers['VERSION'] = version // 让每个请求携带自定义 VERSION 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  const res = response.data
  if (res.code !== 200 && res.code !== 2021 && res.code !== 2017 && res.code !== 3001) {
    // 401:服务器返回检测token有效性：50011非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
    // if (res.code === 401) {
    //   notification.error({
    //     message: '登录失败',
    //     description: res.message
    //   }).then(() => {
    //     store.dispatch('Logout').then(() => {
    //       setTimeout(() => {
    //         window.location.reload()
    //       }, 1500)
    //     })
    //   })
    // }

    notification.error({
      message: '失败提示',
      description: res.message
    })

    return Promise.reject(res)
  } else {
    return res
  }
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
